package com.shiro.exception;

import com.shiro.Result.BaseResult;
import com.shiro.Result.model.ResultModel;
import com.shiro.enums.ResultEnum;
import com.shiro.exception.model.CustomExceptionModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;

/**
 * Created with IntelliJ IDEA.
 * User: dengpeng
 * Date: 2018/6/29
 * Time: 11:34
 * Description: 异常拦截
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 服务器内部错误
     *
     * @param e       {@link Exception}
     * @param request {@link HttpServletRequest}
     * @return ResultModel
     */
    @ExceptionHandler(value = { Exception.class })
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public ResultModel defaultErrorHandler(Exception e, HttpServletRequest request) {

        log.error(request.getRequestURL() + ":\t" + e.getMessage());
        return BaseResult.fail(ResultEnum.FAIL);
    }

    /**
     * 自定义异常返回
     *
     * @param e       {@link CustomExceptionModel}
     * @param request {@link HttpServletRequest}
     * @return {@link ResultModel}
     */
    @ExceptionHandler(value = { CustomExceptionModel.class })
    @ResponseBody
    public ResultModel CustomException(CustomExceptionModel e, HttpServletRequest request) {

        log.error(request.getRequestURL() + ":\t" + e.getMessage());
        return BaseResult.costom(e.getCode(), e.getDescription(), null);
    }

    /**
     * 404
     *
     * @param request {@link HttpServletRequest}
     * @param e       {@link Exception}
     * @return see {@link ResultModel}
     */
    @ResponseBody
    @ExceptionHandler(value = { NoHandlerFoundException.class })
    @ResponseStatus(code = HttpStatus.NOT_FOUND)
    public ResultModel noHandlerFoundException(HttpServletRequest request, Exception e) {

        log.error(request.getRequestURL() + ":\t" + e.getMessage());
        return BaseResult.fail(ResultEnum.URL_NOT_FOUND);
    }

    /**
     * 图片上传异常
     *
     * @param e       {@link Exception}
     * @param request {@link HttpServletRequest}
     * @return see {@link ResultModel}
     */
    @ResponseBody
    @ExceptionHandler(value = { MaxUploadSizeExceededException.class })
    public ResultModel multipartResolver(Exception e, HttpServletRequest request) {

        log.error(request.getRequestURL() + ":\t" + e.getMessage());
        return BaseResult.fail(ResultEnum.LIMITPICTURESIZE);
    }
}
